import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import type { RouteRecordRaw } from 'vue-router'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册', requiresGuest: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile.vue'),
    meta: { title: '个人中心', requiresAuth: true }
  },
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: () => import('@/views/UserProfile.vue'),
    meta: { title: '用户主页' }
  },
  {
    path: '/post/:id',
    name: 'PostDetail',
    component: () => import('@/views/PostDetail.vue'),
    meta: { title: '文章详情' }
  },
  {
    path: '/write',
    name: 'Write',
    component: () => import('@/views/Write.vue'),
    meta: { title: '写文章', requiresAuth: true }
  },
  {
    path: '/edit/:id',
    name: 'EditPost',
    component: () => import('@/views/EditPost.vue'),
    meta: { title: '编辑文章', requiresAuth: true }
  },
  {
    path: '/admin/categories',
    name: 'CategoryManage',
    component: () => import('@/views/CategoryManage.vue'),
    meta: { title: '分类管理', requiresAuth: true }
  },
  {
    path: '/category/:id',
    name: 'CategoryPosts',
    component: () => import('@/views/CategoryPosts.vue'),
    meta: { title: '分类文章' }
  },
  {
    path: '/admin/tags',
    name: 'TagManage',
    component: () => import('@/views/TagManage.vue'),
    meta: { title: '标签管理', requiresAuth: true }
  },
  {
    path: '/tag/:id',
    name: 'TagPosts',
    component: () => import('@/views/TagPosts.vue'),
    meta: { title: '标签文章' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面不存在' }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 博客系统`
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 已登录，检查token是否有效
    try {
      await userStore.checkLoginStatus()
    } catch (error) {
      // token无效，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
  if (to.meta.requiresGuest && userStore.isLoggedIn) {
    next('/')
    return
  }

  next()
})

export default router
